﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Net;
using System.IO;
using Documents.web.Models;
using Documents.web.Helpers;
using Documents.Common.Interfaces;
using Documents.Repository.BusinessObjects;
using Documents.Common.Helpers;

namespace Documents.web.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        private IServiceHelper _documentsHelper;
        private IFormsHelper _formshelper;
        private IPasHelper _pashelper;

        public HomeController()
        {
            //_documentsHelper = new LocalRepositoryServiceHelper();
            _documentsHelper = new NWISRepositoryHelper();
            _formshelper = new LocalFormRepositoryHelper();
            _pashelper = new NWISPasHelper();
       }

        /// <summary>
        /// Overloaded constructor to inject the dependency for the helper, this could be one that communicates with Restful, or SOAP web services
        /// or a local DB, or any other service provider
        /// </summary>
        /// <param name="helper"></param>
        public HomeController(IServiceHelper helper)
        {
            _documentsHelper = helper;
        }

        //[OutputCache(Duration = 600, VaryByParam = "none")]
        public ActionResult Dashboard(int? id)
        {
            DashboardViewModel model = new DashboardViewModel(_pashelper, id, Request["Location"]);

            if (RequestHelper.IsAjaxRequest(Request))
                return PartialView("DashboardDetails", model);
            return View(model);
        }

        public ActionResult DocumentFilterDemo()
        {
            DocumentFilterDemoModel model = new DocumentFilterDemoModel(_pashelper,_documentsHelper);
            return View(model);
        }
    

        public ActionResult PatientLabel(string subjectIdentifiers)
        {
            XmlDocument model = _pashelper.GetPatient(subjectIdentifiers);
            return PartialView(model);
        }


        public ActionResult Patients(string wardCode)
        {
            PatientListType listtype = (PatientListType)Enum.Parse(typeof(PatientListType), Request["listtype"], true);
            PatientListModel model = new PatientListModel(_pashelper, wardCode, "In Patients", listtype);
            if (RequestHelper.IsAjaxRequest(Request))
                return PartialView("PatientLists", model);
            return View(model);
        }

        public ActionResult Discharges(string wardCode)
        {
            PatientListModel model = new PatientListModel(_pashelper, wardCode, "Discharges", PatientListType.Discharges);
            return View("PatientList", model);
        }

        public ActionResult DocumentsPage()
        {
            string subjectidentifiers = Request["subjectIdentifiers"];
            PatientDocumentsViewModel model = new PatientDocumentsViewModel(subjectidentifiers, _documentsHelper, _pashelper);
            return View("Documents", model);
        }


        public ActionResult CareEvents()
        {
            return GetPartialView("CareEvents", "CareEvents");
        }

        public ActionResult Categories(Guid? parentCategory)
        {
            return GetPartialView(parentCategory == null ? "Categories" : string.Format(@"Categories/{0}", parentCategory.ToString()), "CategoryList");
        }

        public ActionResult Documents(Guid? categoryID)
        {
            return GetPartialView(categoryID == null ? "Documents" : string.Format(@"Documents/{0}", categoryID.ToString()), "DocumentList");
        }

        public ActionResult DocumentType(string documentType)
        {
            return GetPartialView(string.Format(@"Documents/{0}/?subjectIdentifiers={1}", documentType, Request["subjectIdentifiers"]), "DocumentList");
        }

        public ActionResult CareEvent(string careEventID)
        {
            return GetPartialView(string.Format(@"CareEvent/{0}",careEventID), "DocumentList");
        }
        
        public ActionResult Document(Guid documentID)
        {
            return GetPartialView(string.Format(@"Document/{0}",documentID), "Document");
        }

        public ActionResult History(Guid DocumentSetID)
        {
           // XmlDocument model = _documentsHelper.Get(string.Format(@"History/{0}",DocumentSetID.ToString()));
            //model.Save(Server.MapPath(@"/"+"History.xml"));

            return GetPartialView(string.Format(@"History/{0}",DocumentSetID.ToString()), "History");
        }

        public ActionResult Revoke(Guid DocumentID)
        {
            return GetPartialView(string.Format(@"Revoke/{0}",DocumentID.ToString()), "Document");
        }

        public ActionResult Edit(Guid DocumentID)
        {
            return GetPartialView(string.Format(@"Edit/{0}",DocumentID.ToString()),"Document");
        }

        private ActionResult GetPartialView(string actionUrl, string viewName)
        {
            XmlDocument model = _documentsHelper.Get(actionUrl);
            return PartialView(viewName, model);
        }


        public ActionResult Create(string DocumentType)
        {
            // For creation, we need to retrieve the form associated with this document type
            string url = @"http://localhost:8080/forms/nhs/corresponance/discharge-advice-letter/v1/?documentId=00000000-0000-0000-0000-000000000000&sessionId=00000000-0000-0000-0000-000000000000&orbeon-embeddable=true&subjectIdentifiers=HospitalNumber\Z100080,NHS\3795624191&duplicate=False&wcpsessionid=45hklsnro2n1rx45x1qx2455";
            RedirectResult result = new RedirectResult(url);
            return result;
        }

        [HttpPost]
        public ActionResult Store()
        {
            string postvars= "documentauthor=Peter+Phillips&documenttitle=I+just+created+this";
            foreach (string param in Request.Form)
                postvars += string.Format("&{0}={1}", param, Request.Form[param]);

            string url = @"Store";
            XmlDocument result = _documentsHelper.Post(url, postvars);
            return new ContentResult
            {
                Content = result["storeresult"]["documentid"].InnerText
            };
        }
    }
}
